//
//  EPCHomeController.swift
//  Weibo
//
//  Created by 吴林峰 on 01/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import UIKit

private let cellID = "cellID"

class EPCHomeController: EPCBaseTableController {

    fileprivate lazy var statusListViewModel = EPCStatusListViewModel()
    
    var isPullUp = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    
    override func loadData() {
        
        statusListViewModel.loadStatus(isPullUp: isPullUp) { (isSuccess, shouldRefresh) in
            
            self.refreshControl?.endRefreshing()
            
            self.isPullUp = false
            
            if shouldRefresh {
                
                self.tableView?.reloadData()
            }
        }
    }
    
    @objc fileprivate func showFriend() {
        navigationController?.pushViewController(EPCDemoController(), animated: true)
    }
}


extension EPCHomeController {
    
    override func setupTableview() {
        
        super.setupTableview()
        
        navItem.leftBarButtonItem = UIBarButtonItem.init(title:"好友", target: self, action: #selector(showFriend))
        
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
        
        setupNavTitle()
    }
    
    func setupNavTitle() {
        
        let title = EPCNetworking.shareManager.userAccount.screen_name
        
        let titleButton = EPCHomeTitleButton.init(title: title)
        
        titleButton.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
        
        navItem.titleView = titleButton
    }
    
    func clickTitleButton(btn: UIButton) {
        
        btn.isSelected = !btn.isSelected
    }
}

extension EPCHomeController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID)
        
        cell?.textLabel?.text = statusListViewModel.statusList[indexPath.row].text
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // Pull-up refresh: To determine whether it is the last line and isPullUp state is false
        
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0 {
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        if (section == indexPath.section)
            && (count - 1 == row)
            && !isPullUp {
            
            isPullUp = true
            
            loadData()
        }
    }
}
